package com.cqjtu.eecs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqjtu.eecs.entity.Permission;
import com.cqjtu.eecs.entity.Role;
import com.cqjtu.eecs.entity.User;
import com.cqjtu.eecs.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义用户登录逻辑
 * @author  luojun
 * @since 2022-03-04
 */

@Service
public class UserDetailsServiceImpl implements UserDetailsService{
    @Autowired
    private  IUserService userService;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 根据用户名获取用户
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, s));
        if (user == null)
            throw new UsernameNotFoundException("用户名或密码错误");
        // 通过uid获取用户的角色List
        List<Role> roleList = userService.listRoleByUid(user.getUid());
        // 通过uid获取用户的权限list
        List<Permission> permissionList = userService.listPermissionByUid(user.getUid());
        Set<GrantedAuthority> authorities = new HashSet<>(); // 角色权限集合
        // 将角色放入集合,需要拼接ROLE_
        for (Role role:roleList) {
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        // 将权限放入集合
        for (Permission permission:permissionList){
            authorities.add(new SimpleGrantedAuthority(permission.getName()));
        }
        org.springframework.security.core.userdetails.User userDetail =
                new org.springframework.security.core.userdetails.User(user.getUsername(),
                        user.getPassword(),
                        authorities);
        return userDetail;
    }
}
